var utils = require('../../utils/utils');
var exerciseTypes = utils.exerciseTypes
var stages = utils.stages

var app = getApp()


const {
	HttpPost,URL,timestampToTime
} = require('../../utils/utils');

var exercises = []
for (let key in exerciseTypes) {
  if (key != "stand") {
    exerciseTypes[key].id = key
    exercises.push(exerciseTypes[key])
  }
}

const uploadInterval = 5000

var defaultType = "stand"
var defaultCostSpeed = exerciseTypes[defaultType].costSpeed
const defaultStage = "slow"


Page({
  data: {
    exerciseType: defaultType,
    typeData: exerciseTypes[defaultType],

    innerAudioContext: null,
    costSpeed: defaultCostSpeed,
    timer: null,

    todayCost: 0,
    totalCost: 0,

    exercises: exercises,

    // userAnimation:{},

    globalData: null,

    nickNameFocus: false,

    startSpeedUpTime: 0,
    lastSpeedUpTime: 0, // 上一个点击时间，两次点击间隔>500ms要重置
    stage: defaultStage,

  },

  changeNameOverEventListener: function(e) {
    // console.log("changeNameOverEventListener", e)
    if (e.detail.newName){
      app.globalData.name = e.detail.newName
    }
    this.setData({
      showModal: false
    })
  },
  onClickTheme: function (e) {
   console.log("onClickTheme", e)
    app.changeTheme()
    this.setData({
      globalData: app.globalData
    })
  },
  onClickName: function (e) {
    this.setData({
      showModal: true
    })
  },
  onClickFlappyBird(e){
    wx.navigateTo({
      url: '/pages/game/game'
    })
	},
	onClick2048(e){
    wx.navigateTo({
      url: '/pages/2048/2048'
    })
	},
	onClickTetris(e){
    wx.navigateTo({
      url: '/pages/tetris/tetris'
    })
	},	
	onClickSaolei(e){
    wx.navigateTo({
      url: '/pages/saolei/saolei'
		})
	},
	onClickMole(e){
    wx.navigateTo({
      url: '/pages/mole/mole'
		})
	},
  onClickPlaneWar(e){
    wx.navigateTo({
      url: '/pages/planewar/planewar'
    })
  },
  onClickGem(e){
    wx.navigateTo({
      url: '/pages/gem/gem'
    })
  },
  onShow: function (options) {
    this.startInter()
    this.playTypeMusic(this.data.exerciseType)
  },

  onHide: function (options) {
    this.endInter()
    this.stopTypeMusic()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    // "shareAppMessage"表示“发送给朋友”按钮，"shareTimeline"表示“分享到朋友圈”按钮
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'], // 需要显示的转发按钮名称列表.合法值包含 "shareAppMessage"、"shareTimeline"
      success(res) {},
      fail(e) {
        // console.log(e);
      }
    });
		var todayStr = utils.getNowFormatDate()
    var [openid,runtype] = await app.getOpenid()		// 执行这里卡住的时候就加载index了，会获取不到URL

		var dbData = await this.selectRecord()
		if (dbData){
			if (dbData.today != todayStr){
				dbData.todaycost = 0
				dbData.today = todayStr
			}
			app.globalData.name = dbData.name
			app.globalData.today = dbData.today
			this.updateCostImpl(dbData.todaycost, dbData.totalcost)
			this.setData({globalData: app.globalData,});
		}

    this.data.speedUpTimer = setInterval(res=>{
      this.updateSpeedUp()
    }, 500);

  },
  async uploadCost(todayStr) {
    let res = await HttpPost('saverecord',{
      exercisedata:{
        todaycost: app.globalData.todayCost,
        totalcost: app.globalData.totalCost,
        today: todayStr,
				name: app.globalData.name,
				openid:app.globalData.openid,
      }
    })
    if (res.code != 0) {
        wx.showToast({
          title: '系统错误：' + res.msg,
        })
        return
    }
  },

  async selectRecord(){
    let res = await HttpPost('getrecord',{
    })
    if (res.code != 0) {
        wx.showToast({
          title: '系统错误：' + res.msg,
        })
        return
		}
		return res.exercisedata
  },
  getUserProfile: function (callback) {
    if (app.globalData.name) {
      callback()
      return
    }
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        // console.log("getUserProfile", res)
        app.globalData.name = res.userInfo.nickName
      },
      fail: (res) => {
        // console.log("mine getUserProfile res", res)
      },
      complete: (res) => {
        callback()
      }
    })
  },

  onChoose: function (e) {
    var that = this

    var type = e.target.id
    var typeData = exerciseTypes[type]
    if (!typeData) {
      console.error("onChoose invalid type e", e)
      return
    }
    var oldType = that.data.exerciseType
    if (oldType == type) {
      that.reset()
      return
    }

    that.switchType(type)

    if (!that.timer) {
      that.startInter()
    }
  },

  switchType: function (type) {
    const typeData = exerciseTypes[type]
    let that = this
    this.setData({
      typeData: {
        gif: ""
      }
    }, () => { // 防止上一个image残留
      that.setData({
        exerciseType: type,
        typeData: typeData,
        exercises: exercises,
        stage: defaultStage
      }, () => {})
      that.playTypeMusic(type)
    })
  },

  updateSpeedUp(click) {

    let typeData = exerciseTypes[this.data.exerciseType]
    if (!typeData.speedUp) {
      return
    }

    const now = Date.now()
    var thisStage = stages[this.data.stage]

    if (click) {
      if (this.data.startSpeedUpTime == 0) {
        this.data.startSpeedUpTime = now
        this.data.lastSpeedUpTime = now
      } else {
        if (now - this.data.lastSpeedUpTime >= 500) {
          this.data.startSpeedUpTime = now
          this.data.lastSpeedUpTime = now
        } else {
          if (now - this.data.startSpeedUpTime < thisStage.time * 1000) {
            this.data.lastSpeedUpTime = now
          } else { // 进入下一个stage
            this.data.startSpeedUpTime = now
            this.data.lastSpeedUpTime = now
            if (thisStage.next) {
              this.setData({stage: thisStage.next})
              this.speedUpMusic(thisStage.musicRate)
              // console.log("onClickSpeedUp", thisStage.next)
            }
          }
        }
      }
    }else{
      if (this.data.stage != defaultStage){   // 超过
        if (now - this.data.lastSpeedUpTime >= 10 * 1000){
          this.data.startSpeedUpTime = 0
          this.data.lastSpeedUpTime = 0
          this.setData({stage:defaultStage})
          this.speedUpMusic(stages[defaultStage].musicRate)
          // console.log("onClickSpeedUp dec", defaultStage)
        }
      }
    }

  },

  onClickSpeedUp: function (e) {
    this.updateSpeedUp(true)
  },

  reset: function () {
    // console.log("reset", this.data)
    if (this.data.typeData.costSpeed > 0) {
      var type = 'stand'
      this.switchType(type)
      this.endInter()
    }
  },

  startInter: function () {
    if (this.data.timer) {
      return
    }
    var that = this;
    that.data.timer = setInterval(
      function () {
        that.updateCost()
      }, uploadInterval);
  },
  /**
   * 结束定时器
   */
  endInter: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.data.timer = null
    }
  },

  updateCost: function () {
    if (this.data.typeData.costSpeed <= 0) {
      return
    }
    let todayStr = utils.getNowFormatDate()
    var thisStage = stages[this.data.stage]
    let add = this.data.typeData.costSpeed * thisStage.ratio * uploadInterval / 1000
    let [todayCost, totalCost] = [this.data.todayCost + add, this.data.totalCost + add]
    if (todayStr != this.data.globalData.today){
     this.data.globalData.today = todayStr
     todayCost = add
    }
    this.updateCostImpl(todayCost, totalCost)
    this.uploadCost(todayStr)
    app.showOpacity(this, 1, '消耗 ' + utils.formatNumber(add) + ' 卡路里')
  },

  updateCostImpl: function (todayCost, totalCost) {
    this.setData({
      todayCost: Math.round(todayCost * 100) / 100,
      totalCost: Math.round(totalCost * 100) / 100,
    })
    app.globalData.todayCost = this.data.todayCost
    app.globalData.totalCost = this.data.totalCost

  },

  playTypeMusic: function (type) {
    this.stopTypeMusic()
    if (type != 'stand') {
      let music = "music/" + type + ".mp3"
      let innerAudioContext = exerciseTypes[type].innerAudioContext
      if (!innerAudioContext) {
        innerAudioContext = wx.createInnerAudioContext({
          useWebAudioImplement: false,
        })
        exerciseTypes[type].innerAudioContext = innerAudioContext
      }
      innerAudioContext.loop = true
      innerAudioContext.playbackRate = 0.8
      innerAudioContext.src = music
      let p = innerAudioContext.play()
      this.data.innerAudioContext = innerAudioContext
      // console.log("playTypeMusic", type, music, typeof p)
    }
  },
  stopTypeMusic: function () {
    if (this.data.innerAudioContext) {
      this.data.innerAudioContext.pause() // 停止
      // this.data.innerAudioContext.destroy()
      this.data.innerAudioContext = null
    }
  },

  speedUpMusic(musicRate) {
    let innerAudioContext = this.data.typeData.innerAudioContext
    innerAudioContext.playbackRate = musicRate
  },

  onShareAppMessage: function () {
    let title = "一起来云上健身吧"
    return {
      title: title,
      path: '/pages/index/index',
    }
  },

  /**
   * 模拟隐私接口调用，并触发隐私弹窗逻辑
   */
  requirePrivacyAuthorize() {
    if (wx.requirePrivacyAuthorize) {
      console.warn("当前基础库支持api wx.requirePrivacyAuthorize");
      wx.requirePrivacyAuthorize({
        success: res => {
          console.log('用户同意了隐私协议 或 无需用户同意隐私协议');
          //用户同意隐私协议后给昵称输入框聚焦
          this.setData({
            nickNameFocus: true
          })
        },
        fail: res => {
          console.log('用户拒绝了隐私协议');
        }
      })
    } else {
      console.warn("当前基础库不支持api wx.requirePrivacyAuthorize");
      this.setData({
        nickNameFocus: true
      })
    }
  },


})